import { Context, Schema, h } from 'koishi'
import sharp from 'sharp';

export const name = 'money-seeker'

export interface Config {
  guildIdList: string[]; // 群组ID列表
  keywordList: string[]; // 关键词列表
  reportQqUserIdList: string[]; // 需要报告的用户ID列表

  veboseConsoleOutput?: boolean; // 是否输出调试信息
}

export const Config: Schema<Config> = Schema.intersect([

  Schema.object({
    guildIdList: Schema.array(String)
      .default(["259248174"])
      .description("需要监听的群组ID列表。"),
    keywordList: Schema.array(String)
      .default(["怎么", "教", "解", "问"])
      .description("需要监听的关键词列表。"),
    reportQqUserIdList: Schema.array(String)
      .default(["1830540513"])
      .description("需要报告的用户ID列表。")
  }).description("基础设置"),

  Schema.object({
    veboseConsoleOutput: Schema.boolean()
      .default(false)
      .description("是否输出调试信息。")
  }).description("调试设置")  

])

export function apply(ctx: Context, config: Config) {

  ctx.on('message', async (session) => {

    if ( !session.guildId ) {
      if (ctx.config.verboseConsoleOutput) 
        ctx.logger.info(`[money-seeker] 非群组消息，跳过。`);
      return;
    }

    if ( !config.guildIdList.includes(session.guildId) ) {
      if (ctx.config.verboseConsoleOutput) 
        ctx.logger.info(`群组ID ${session.guildId} 不在列表中，跳过。`);
      return;
    }

    let hit: Boolean = false;
    let hitKeywordList: string[] = [];
    for (const keyword of config.keywordList) {
      if (session.content.includes(keyword)) {
        hit = true;
        hitKeywordList.push(keyword);
      }
    }

    if ( hit === false ) return;

    let hitMsg = `[money-seeker]\n===================\n`;
    const gid = session.guildId;
    hitMsg += `群组ID: \t ${gid} \n`;

    const guildObj = await session.bot.getGuild(gid);
    const guildName = guildObj.name;
    hitMsg += `群组名称: \t ${guildName} \n`;

    const guildAvatarUrl = `https://p.qlogo.cn/gh/${gid}/${gid}/640`;
    const guildAvatarBase64 = await fetchAndResizeImageTo64Base64(ctx, guildAvatarUrl);
    // hitMsg += `群头像: ` + h.image( guildAvatarUrl ) + ` \n`;
    hitMsg += `群头像: \t ` + h.image(guildAvatarBase64) + ` \n`;

    hitMsg += `--------------------\n`;

    const uid = session.userId;
    hitMsg += `用户ID: \t ${uid} \n`;

    hitMsg += `用户昵称: \t ${session.author?.nick || session.author?.nickname} \n`;

    hitMsg += `用户名称: \t ${session.author?.name || session.author?.username} \n`;

    const userObj = await session.bot.getUser(uid);
    const userAvatarBase64 = await fetchAndResizeImageTo64Base64(ctx, userObj.avatar);
    // hitMsg += `用户头像: ` + h.image(userObj.avatar) + ` \n`;
    hitMsg += `用户头像: \t ` + h.image(userAvatarBase64) + ` \n`;

    hitMsg += `--------------------\n`;

    hitMsg += `命中的关键词: \t ${hitKeywordList.join('、 ')} \n`;

    hitMsg += `消息内容: \t ${session.content.slice(0,300)} \n`;

    for ( const uid of config.reportQqUserIdList ) {
      await session.bot.sendPrivateMessage(
        uid,
        hitMsg
      )
    }

    if ( config.veboseConsoleOutput)
      ctx.logger.info(hitMsg);

  })  

    /**
   * 下载图片并压缩到长边 ≤ 64，返回 base64（含 data:image/png;base64 前缀）。
   * @param ctx Koishi 的上下文
   * @param imageUrl 图片的 URL
   * @returns Promise<string> base64
   */
  async function fetchAndResizeImageTo64Base64(ctx: Context, imageUrl: string): Promise<string> {
    // 1. 通过 Koishi 的 http.get 下载图片
    const response = await ctx.http.get(imageUrl, { responseType: 'arraybuffer' });
    const inputBuffer = Buffer.from(response);

    // 2. 用 sharp 读取尺寸
    const metadata = await sharp(inputBuffer).metadata();
    const { width, height } = metadata;

    if (!width || !height) {
      throw new Error('无法获取图片尺寸');
    }

    // 3. 计算缩放比例
    const scale = 64 / Math.max(width, height);
    const targetWidth = Math.round(width * scale);
    const targetHeight = Math.round(height * scale);

    // 4. 压缩
    const resizedBuffer = await sharp(inputBuffer)
      .resize(targetWidth, targetHeight)
      .png()
      .toBuffer();

    // 5. 转成 base64
    return `data:image/png;base64,${resizedBuffer.toString('base64')}`;
  }

}
